package com.basic.filter;

import java.util.LinkedList;
import java.util.List;

/**
 * WordNode <br>
 *
 * @author: chat  <br>
 * @date: 2021/5/7 0007  <br>
 */
public class WordKeyNode {

    private int value; // 节点名称

    private List<WordKeyNode> subNodes; // 子节点

    private boolean isLast;// 默认false

    private String key;

    public WordKeyNode(int value, String key) {
        this.value = value;
        this.key=key;
    }

    public WordKeyNode(int value, String key, boolean isLast) {
        this.value = value;
        this.key=key;
        this.isLast = isLast;
    }

    /**
     *
     * @param subNode
     * @return 就是传入的subNode
     */
    private WordKeyNode addSubNode(final WordKeyNode subNode) {
        if (subNodes == null)
            subNodes = new LinkedList<WordKeyNode>();
        subNodes.add(subNode);
        return subNode;
    }

    /**
     * 有就直接返回该子节点， 没有就创建添加并返回该子节点
     *
     * @param value
     * @return
     */
    public WordKeyNode addIfNoExist(final int value, String key, final boolean isLast) {
        if (subNodes == null) {
            return addSubNode(new WordKeyNode(value,key, isLast));
        }
        for (WordKeyNode subNode : subNodes) {
            if (subNode.value == value) {
                if (!subNode.isLast && isLast)
                    subNode.isLast = true;
                return subNode;
            }
        }
        return addSubNode(new WordKeyNode(value,key, isLast));
    }

    public WordKeyNode querySub(final int value) {
        if (subNodes == null) {
            return null;
        }
        for (WordKeyNode subNode : subNodes) {
            if (subNode.value == value)
                return subNode;
        }
        return null;
    }

    public boolean isLast() {
        return isLast;
    }

    public void setLast(boolean isLast) {
        this.isLast = isLast;
    }

    @Override
    public int hashCode() {
        return value;
    }

    public String getKey() {
        return key;
    }
}
